import plistlib
import os
import json
from tkinter import Tk, filedialog
from PIL import Image
import GetTxt

def select_directory(title):
    """弹出选择目录对话框"""
    root = Tk()
    root.withdraw()  # 隐藏主窗口
    root.attributes('-topmost', True)  # 置顶窗口
    directory = filedialog.askdirectory(title=title)
    return directory


def get_frame_info(frame_str):
    inner_str = frame_str[2:-2]  # 结果是 '0,277},{272,181'
    print(inner_str)
    first_brace_end_index = inner_str.find('}')
    part_1 = inner_str[:first_brace_end_index + 1]
    part_1 = part_1.rstrip('}')
    second_part_start_index = inner_str.find(',', first_brace_end_index) + 1
    part_2 = inner_str[second_part_start_index:].strip('{},')

    offset_parts_1 = part_1.split(',')
    part_frame_1_x = int(offset_parts_1[0])
    part_frame_1_y = int(offset_parts_1[1])
    print(f"Image1:{part_frame_1_x}")
    print(f"Image2:{part_frame_1_y}")

    offset_parts_2 = part_2.split(',')
    part_frame_2_x = int(offset_parts_2[0])
    part_frame_2_y = int(offset_parts_2[1])
    print(f"Image3:{part_frame_2_x}")
    print(f"Image4:{part_frame_2_y}")
    return (part_frame_1_x,part_frame_1_y,part_frame_2_x,part_frame_2_y)

def get_rotated(isrotate):
    rotate = bool(isrotate)
    return rotate

def getDicValue(offset_str):
    offset_parts = offset_str[1:-1].split(',')
    if int(offset_parts[0])  >= 0:
        offset_x =abs(int(offset_parts[0]))
        offset_y =abs(int(offset_parts[1]))
    else:
        offset_x = -abs(int(offset_parts[0]))
        offset_y = -abs(int(offset_parts[1]))
    return (offset_x, offset_y)


def loadDire(plist_path, output_dir,width,height,check):
    png_frames_info = {}
    png_file_path = []
    png_full_path=""
    png_info={}
    sub_dir_path = ""
    index = 0
    for sub_dir in os.listdir(plist_path):
        cur_frames_info = {}
        if sub_dir.endswith(".png"):
            png_full_path = os.path.join(plist_path, sub_dir)
            png_file_path.append(png_full_path)
            sub_dir_path = sub_dir
        if sub_dir.endswith(".plist"):
            # 读取 plist 文件
            plist_full_path = os.path.join(plist_path, sub_dir)
            with open(plist_full_path, 'rb') as fp:
                plist_data = plistlib.load(fp)

                frames_dict = plist_data.get('frames', {})

                for png_name, frame_info in frames_dict.items():
                    # 将帧信息存储到字典中，以.png文件名作为键
                    cur_frames_info[png_name] = frame_info
                png_info[index] = cur_frames_info
                index += 1
    i = 0
    for png_path in png_file_path:
        num=0
        print(png_path)
        image_atlas = Image.open(png_path)

        for png_name, frame_info in png_info[i].items():
            print(f"Image: {png_name}")
            print(f"  Frame: {frame_info['frame']}")
            print()
            frame_info_1_x, frame_info_1_y, sizeW, sizeH = get_frame_info(frame_info['frame'])
            offset_x, offset_y = getDicValue(frame_info['offset'])
            sourceSize_x, sourceSize_y = getDicValue(frame_info['sourceSize'])
            rotated_value = get_rotated(frame_info['rotated'])
            if  width or height >=0:
                sourceSize_x=width
                sourceSize_y=height
            back_image = Image.new("RGBA", (sourceSize_x, sourceSize_y))
            back_width, back_height = back_image.size
            # 旋转处理
            if rotated_value == True:
                new_image = image_atlas.crop(
                    (frame_info_1_x, frame_info_1_y, frame_info_1_x + sizeH, frame_info_1_y + sizeW))
                new_image = new_image.transpose(Image.ROTATE_90)
            else:
                new_image = image_atlas.crop(
                    (frame_info_1_x, frame_info_1_y, frame_info_1_x + sizeW, frame_info_1_y + sizeH))
            back_image.paste(new_image, (int(back_width / 2) + offset_x - 24, int(back_height / 2) + offset_y - 18))

            # 创建输出子目录
            # 1. 提取文件名
            file_name = os.path.basename(png_path)

            # 2. 去掉后缀
            base_name = os.path.splitext(file_name)[0]
            output_sub_dir = os.path.join(output_dir, base_name)
            if not os.path.exists(output_sub_dir):
                os.makedirs(output_sub_dir)
            output_path = os.path.join(output_sub_dir, f"{num:2d}.png")
            num += 1
            print(output_path)
            back_image.save(output_path)
        i += 1
    if check:
        GetTxt.getValue(plist_path,output_dir)
def cur_loadDire(png_path,cur_index,plist_path,output_dir,width,height,check):
    png_frames_info = {}
    png_file_path = []
    png_full_path = ""
    png_info = {}
    sub_dir_path = ""
    index = 0
    for sub_dir in os.listdir(plist_path):
        cur_frames_info = {}
        if sub_dir.endswith(".png"):
            png_full_path = os.path.join(plist_path, sub_dir)
            png_file_path.append(png_full_path)
            sub_dir_path = sub_dir
        if sub_dir.endswith(".plist"):
            # 读取 plist 文件
            plist_full_path = os.path.join(plist_path, sub_dir)
            with open(plist_full_path, 'rb') as fp:
                plist_data = plistlib.load(fp)

                frames_dict = plist_data.get('frames', {})

                for png_name, frame_info in frames_dict.items():
                    # 将帧信息存储到字典中，以.png文件名作为键
                    cur_frames_info[png_name] = frame_info
                png_info[index] = cur_frames_info
                index += 1
    num = 0
    print("切割当前",png_path)
    image_atlas = Image.open(png_path)

    for png_name, frame_info in png_info[cur_index].items():
        print(f"Image: {png_name}")
        print(f"  Frame: {frame_info['frame']}")
        print()
        frame_info_1_x, frame_info_1_y, sizeW, sizeH = get_frame_info(frame_info['frame'])
        offset_x, offset_y = getDicValue(frame_info['offset'])
        sourceSize_x, sourceSize_y = getDicValue(frame_info['sourceSize'])
        rotated_value = get_rotated(frame_info['rotated'])
        if width or height >= 0:
            sourceSize_x = width
            sourceSize_y = height
        back_image = Image.new("RGBA", (sourceSize_x, sourceSize_y))
        back_width, back_height = back_image.size
        # 旋转处理
        if rotated_value == True:
            new_image = image_atlas.crop(
                (frame_info_1_x, frame_info_1_y, frame_info_1_x + sizeH, frame_info_1_y + sizeW))
            new_image = new_image.transpose(Image.ROTATE_90)
        else:
            new_image = image_atlas.crop(
                (frame_info_1_x, frame_info_1_y, frame_info_1_x + sizeW, frame_info_1_y + sizeH))
        back_image.paste(new_image, (int(back_width / 2) + offset_x - 24, int(back_height / 2) + offset_y - 18))
        # 创建输出子目录
        # 1. 提取文件名
        file_name = os.path.basename(png_path)

        # 2. 去掉后缀
        base_name = os.path.splitext(file_name)[0]
        output_sub_dir = os.path.join(output_dir, base_name)
        if not os.path.exists(output_sub_dir):
            os.makedirs(output_sub_dir)
        output_path = os.path.join(output_sub_dir, f"{num:2d}.png")
        num += 1
        print(output_path)
        back_image.save(output_path)
    if check:
        # 分割文件路径为目录和文件名
        directory = os.path.dirname(png_path)
        filename = os.path.basename(png_path)

        # 分割文件名为文件名和后缀
        name, ext = os.path.splitext(filename)

        # 更换后缀为 .json
        new_filename = name + ".plist"
        new_path = os.path.join(directory, new_filename)
        print("new_path",new_path)
        GetTxt.getCur_Value(output_dir,png_path,new_path)

if __name__ == "__main__":
    print("请选择包含序列帧目录的输入文件夹：")
    input_directory = select_directory("选择输入目录")
    if not input_directory:
        print("未选择输入目录，程序退出。")
        exit()

    print("请选择裁剪后图片的输出文件夹：")
    output_directory = select_directory("选择输出目录")
    if not output_directory:
        print("未选择输出目录，程序退出。")
        exit()

    loadDire(input_directory,output_directory)
    print("所有任务已完成！")

